import { get, add } from "../../utils/db"
import { upload, multiUpload } from "../../utils/upload"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    files: [],     //临时图片列表
    typeList: [],    //分类列表
    name: "",      //菜谱名称
    typeid: 0,   //分类id
    intro: "",   //菜谱做法
    error: "",   //错误提示信息
  },
  async onLoad() {
    let result = await get({ collection: "type", where: {} }).catch(err => console.error(err))
    // console.log(result)
    this.setData({
      typeList: result.data
    })

    //页面加载，给typeid添加默认值
    this.setData({
      typeid: this.data.typeList[0]._id
    })

  },
  //选择图片
  handleSelect(e) {
    // console.log(e)
    let arr = e.detail.tempFilePaths;
    let result = arr.map(item => {
      return { url: item }
    })
    this.setData({
      files: result
    })
  },
  //选择菜谱分类
  selectType(e) {
    // console.log(e)
    this.setData({
      typeid: e.detail.value
    })
  },
  //输入菜谱做法
  handleInput(e) {
    // console.log(e)
    this.setData({
      intro: e.detail.value
    })
  },
  //发布菜谱
  async handleSubmit() {
    //检测表单
    if (this.data.name == "") {
      this.setData({
        error: "请填写菜单名称"
      })
      return;
    }
    if (this.data.files.length == 0) {
      this.setData({
        error: "请选择图片"
      })
      return;
    }
    if (this.data.intro.length == 0) {
      this.setData({
        error: "请填写菜谱做法"
      })
      return;
    }

    wx.showLoading({
      title: '正在提交',
      mask: true
    })
    //批量上传图片
    let image = await multiUpload(this.data.files).catch(err => {
      console.error(err)
    })
    let userInfo = wx.getStorageSync('userInfo')
    //操作数据库
    let formData = {
      typeid: this.data.typeid,
      name: this.data.name,
      image: image,
      intro: this.data.intro,
      avatarUrl: userInfo.avatarUrl,
      nickName: userInfo.nickName,
      views: 0,
      likes: 0,
      addtime: new Date().getTime()
    }
    let result = add({ collection: "menu", data: formData }).catch(err => {
      console.error(err)
    })

    wx.hideLoading()    //隐藏loading框
    wx.showToast({
      title: '成功添加',
    })
    setTimeout(() => {
      wx.reLaunch({
        url: '/pages/my/my',
      })
    }, 1500);


  }


})